
<template>
  <views class="facilitator_enterprise_list">
     <!-- 审核start -->
    <modelBox :show="check_show">
      <div class="check_enterprise_status">
        <viewTitle :title="'审核费率'" :border="false"></viewTitle>
        <div class="check_enterprise flex flexC flexJp">
          <div class="flex flexJ center">
            <div class="title">企业名称:</div>
            <div class="content">{{check_enterprise_name}}</div>
          </div>
          <div class="flex flexJ center">
            <div class="title">审核状态:</div>
            <div class="content">
              <el-select v-model="check_draft_status">
                <el-option
                  v-for="item in check_draft_status_list"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <!-- 确认 取消 -->
        <div class="confirm_cancel flex center">
          <el-button @click="check_show = !check_show">取消</el-button>
          <el-button type="primary" @click="check">确定</el-button>
        </div>
      </div>
    </modelBox>
    <!-- 审核end -->
    <viewTitle :title="'企业协议费率列表'" :border="false"></viewTitle>
    <!-- 费率信息start -->
    <el-dialog title="费率信息" :visible.sync="dialogTableVisible">
        <span>标准费率：{{enterpriseRate.standard_rate}}</span>
        <el-table :data="enterpriseRate.rate_list" v-if="enterpriseRate.region_type_name != '不累计'" :header-cell-style="{background:'#f9f9f9'}">
            <el-table-column property="range" label="费率政策" width="300"></el-table-column>
            <el-table-column property="region_rate" :label="enterpriseRate.region_type_name" ></el-table-column>
        </el-table>
    </el-dialog>
    <!-- 费率信息 end -->
    <!-- 编辑费率start -->
    <el-dialog  title="编辑费率" :close-on-click-modal="false" :visible.sync="editDialogTableVisible" ref="bjfl">
      <el-form ref="enterpriseRate" label-width="auto" :inline="true" class="edit_dialog flex flexC flexJ">
        <el-form-item label="协议时间:">
          <el-date-picker v-model="enterpriseRate.protocol_time" :default-time="['0:00:00','23:59:59']" value-format="timestamp"  type="datetimerange"  range-separator="-"  start-placeholder="开始时间"
          end-placeholder="结束时间"  size="mini">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="协议文件:">
          
          <el-upload  class="flex"  
            multiple
            list-type="picture-card"
            :action="upload_file"  
            :on-preview="uploadProtocolPreview"  
            :on-success="uploadProtocolSuccess"	
            :on-remove="removeProtocolImg"
            :file-list="enterpriseRate.protocolFileList">
            <!-- :file-list="fileList"> -->

              <i class="el-icon-plus"></i>
          </el-upload>
         
        </el-form-item>
        <el-form-item label="标准费率:">
          <el-input type="text" size="mini" clearable placeholder="请输入标准费率值" ref="standard_rate" v-model="enterpriseRate.standard_rate" ></el-input>
        </el-form-item>
        <el-form-item label="费率政策:">
            <el-select v-model="enterpriseRate.region_type" size="mini" @change="updateRegionType" >
              <el-option  :selected="enterpriseRate.region_type == item.value"  v-for="item in region_type_list"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="阶梯费率:" v-show="isShowRegion" >
          <el-col :span="5" style="font-size:18px">
              <i class="el-icon-circle-plus-outline" @click="add_input"></i>
          </el-col>
          <el-col :span="5"  style="margin-left:20px;font-size:18px">
              <i class="el-icon-remove-outline" @click="remove_input"></i>
          </el-col>
        </el-form-item>
        
        <el-form-item  v-show="isShowRegion" v-for="(item, index) in enterpriseRate.rate_list" :key="index">
              <el-col :span="7">
                <el-input type="text" size="mini" clearable placeholder="请输入起始金额" v-model="item.money_region_start" ></el-input>
              </el-col>
              <el-col :span="1" style="text-align:center">-</el-col>
              <el-col :span="7">
                <el-input type="text" size="mini" clearable placeholder="请输入截至金额" v-model="item.money_region_end"></el-input>
              </el-col>
              <el-col :span="1.5" style="margin-left:10px">费率:</el-col>
              <el-col :span="5">
                <el-input type="text" size="mini" clearable placeholder="请输入阶梯费率" v-model="item.region_rate" />
              </el-col>
        </el-form-item>
        <el-form-item>
          <el-button  @click="editDialogTableVisible = !editDialogTableVisible">取消</el-button>
          <el-button type="primary" @click="submitEnterpriseRate">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑费率end -->
    <!-- 查看协议图片预览 start -->
    <el-dialog :visible.sync="protocolDialogVisible">
      <img width="100%" :src="protocolDialogImageUrl" alt="">
    </el-dialog>
    <!-- 查看协议图片预览 end -->

    <!-- 搜索栏 服务商端 -->
    <div class="search flex flexR">
      <!-- 企业编号-企业名称-企业状态-上级代理商编号-所属服务商-客户经理-提交时间 -->
      <el-form ref="form" label-width="auto" :inline="true">
          <el-form-item label="企业编号:">
            <el-input v-model="form.enterprise_sn" placeholder="请输入企业编号" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item label="企业名称:">
            <el-input v-model="form.enterprise_name" placeholder="请输入企业名称" :clearable="true"></el-input>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="query">查询</el-button>
              <el-button @click="reset">重置</el-button>
          </el-form-item>
      </el-form>
      
    </div>
    <!-- 展示列表 -->
    <div class="table_list">
      <el-table
        border
        :data="tableData"
        style="width: 100%;max-width:none;"
        :header-cell-style="getRowClass"
        :select-on-indeterminate="true"
        :fit="true"
        :lazy="true"
        max-height="450"
      >
        <el-table-column fixed="left" type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="enterprise_sn" label="企业编号" ></el-table-column>
        <el-table-column prop="enterprise_name" label="企业名称"></el-table-column>
        <el-table-column prop="protocol_start_time" label="协议开始时间"></el-table-column>
        <el-table-column prop="protocol_end_time" label="协议结束时间"></el-table-column>
        <el-table-column prop="standard_rate" label="标准充值费率" ></el-table-column>
        <el-table-column  label="签约协议" width="100">
            <template slot-scope="scope">
                <el-link type="primary" @click="loaddown(scope.row.protocol_img)" target="_blank" v-if="scope.row.protocol_img != ''" >下载协议</el-link>
            </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template slot-scope="scope" class="table_operation flex flexR">
            <!-- 查看费率start -->
            <el-button @click="look(scope.row.enterprise_facilitator_draft_id)">查看</el-button>
            <!-- 查看费率end -->
            <el-button type="primary" @click="edit(scope.row.enterprise_facilitator_draft_id)">编辑</el-button>
            <!-- 审核start -->
            <el-button  type="success"  v-if="parseInt(scope.row.status) === 0"  @click="check_modal_show(scope.row.enterprise_facilitator_draft_id, scope.row.enterprise_name)">审核</el-button>
            <!-- 审核end -->
          </template>
        </el-table-column>
      </el-table>
      <div class="flex flexR paging">
        <el-pagination
          style="background:#fff; padding:10px 0"
          background
          layout="total, sizes,prev, pager, next, jumper"
          @size-change="handleSizeChange($event)"
          @current-change="changePage($event)"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.page_size"
          :total="pagination.total_count"
          :current-page="pagination.current_page"
          :page-count="pagination.page_count"
        ></el-pagination>
      </div>
    </div>
  </views>
</template>



<script>
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'


export default {
  data() {
    return {
      // fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      dialogTableVisible: false,     //查看费率框是否展示
      editDialogTableVisible: false,    //编辑费率框是否展示
      protocolDialogVisible: false,     //协议图片展示
      protocolDialogImageUrl: '',       //协议图片预览
      isShowRegion: false,              //是否展示阶梯费率
      check_show : false, //审核企业模态框显示
      check_enterprise_facilitator_draft_id : 0, //对应的审核企业企业草稿ID
      check_enterprise_name : '', //对应的审核企业名称
      check_draft_status: 1, //提交的审核企业状态值
      check_draft_status_list: [
        { value: 1, label: "审核通过" },
        { value: 2, label: "审核不通过" }
      ], //可选审核状态值列表
      form: {
        enterprise_sn: "", // 企业编号
        enterprise_name: "", // 企业名称
      },
      select_enterprise_facilitator_draft_id:0,     //被选中的协议费率ID
      tableData: [],
      region_type_list:[{value:0, label:'不累计'},{value:1, label:'按月累计'},{value:2, label:'按年累计'}],             //费率政策
      enterpriseRate: {
        protocol_time: [],      //协议合同时间
        protocolFileList: [],   //协议图片文件
        standard_rate:'',       //标准费率
        region_type: '',        //费率政策
        rate_list:[{money_region_start:'', money_region_end: '', region_rate: ''}],           //阶梯费率

      },
      pagination: {
        //分页数据
        page_start: 0, //搜索开始页码
        current_page: 0, //当前页码
        page_count: 0, //总页数
        page_size: 10, //每页数量
        total_count: 0 //总数量
      }
    };
  },
  computed: {
    post_data() {
      let data = {};
      data.enterprise_sn = this.form.enterprise_sn;
      data.enterprise_name = this.form.enterprise_name;
      data.pagination = this.pagination;
      return data;
    },
    upload_file(){
        return  this.$store.getters.uploadFile;
    },            
    protocolFileListComputed(){
      return  this.enterpriseRate.protocolFileList ? this.enterpriseRate.protocolFileList : [];
    }
    
  },

  mounted() {
    this.$setRouteTitle();
    //进来就调首页列表接口
    this.query();
  },
  methods: {
    //    修改第一行样式
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background: #FAFAFA ";
      } else {
        return "";
      }
    },
    handleSizeChange(page_size) {
      //变动每页数量时
      this.pagination.page_size = page_size;
      this.query();
    },
    changePage(current_page) {
      //切换页码时
      this.pagination.page_start = current_page;
      this.query();
    },
    async query() {
      //企业协议费率列表
      let { code, msg, data } = await this.$api.sendSync(
        this.$mapapi.f_enterpriseDraftList,
        this.post_data
      );
      if (code != 200 && code != 501)   return  this.$message.error(msg);
      this.tableData = data.list;
      this.pagination = data.pagination;
    },
    reset() {
      //重置
      this.form = {
        enterprise_sn: "",
        enterprise_name: "",
      };
      this.query();
    },
    getFile(url){
        return new Promise((resolve, reject) => {
           axios({
                method:'get',
                url,
                responseType: 'arraybuffer'
            }).then(data => {
                resolve(data.data)
            }).catch(error => {
                reject(error.toString())
            })
        })
    },

    /* 下面为查看/编辑协议费率部分 start */
    loaddown(protocol_img){         //下载协议
        const data = protocol_img // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
            const zip = new JSZip()
            const cache = {}
            const promises = []
            data.forEach(item => {
                const promise = this.getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
                    const arr_name = item.split("/")
                    const file_name = arr_name[arr_name.length - 1] // 获取文件名
                    zip.file(file_name, data, { binary: true }) // 逐个添加文件
                    cache[file_name] = data
                })
                promises.push(promise)
            })

            Promise.all(promises).then(() => {
                zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
                    FileSaver.saveAs(content, "打包下载.zip") // 利用file-saver保存文件
                })
            })
    },
    look(enterprise_facilitator_draft_id){        //查看费率
        this.dialogTableVisible = true;
        let {code, msg, data}   =   this.$api.sendSync(this.$mapapi.f_enterpriseDraftRate, {enterprise_facilitator_draft_id});
        if(code != 200&&code!=501)  return  this.$message.error(msg);
        this.enterpriseRate = data;
        if(data.protocol_img != ''){
            for(let val of data.protocol_img){
              this.enterpriseRate.protocolFileList.push({uid:Date.now(), img:val, name: ''});
            }
        }else{
          this.enterpriseRate.protocolFileList = [];
        }    
        if(data.rate_list.length > 0){
            for(let val of this.enterpriseRate.rate_list){      //将阶梯费率起始、结束金额做成合成一个字段 range
                val.range = val.money_region_start + '~' + val.money_region_end;
            }
            this.isShowRegion = true;
        }
    },
    edit(enterprise_facilitator_draft_id){         //编辑费率
        this.editDialogTableVisible = true;
        let protocol_file_list = [];
        let {code, msg, data}   =   this.$api.sendSync(this.$mapapi.f_enterpriseDraftRate, {enterprise_facilitator_draft_id});
        if(code != 200&&code!=501){
            this.$message.error(msg);
            return;
        }
        this.enterpriseRate = data;
        this.enterpriseRate.protocolFileList = [];
        if(data.protocol_img != ''){
            for(let i in data.protocol_img){
              this.enterpriseRate.protocolFileList.push({ url:data.protocol_img[i], name: i});
            }
        }
        //再将协议图片插入数组中
        this.select_enterprise_facilitator_draft_id = enterprise_facilitator_draft_id;
        if(parseInt(data.region_type) > 0)   this.isShowRegion = true;
    },
    add_input(){            //阶梯费率中增加一行阶梯费率input 框，暂设最多5个阶梯
        if(this.enterpriseRate.rate_list.length > 4)    return;
        this.enterpriseRate.rate_list.push({'money_region_start':'', 'money_region_end':'', 'region_rate':''});
    },
    remove_input(){         //阶梯费率中移除最后一行阶梯费率input 框
        if(this.enterpriseRate.rate_list.length === 1)   return;
        this.enterpriseRate.rate_list.pop();
    },
    updateRegionType(){     //切换费率政策时，控制下面的阶梯费率是否显示
        if(this.enterpriseRate.region_type){
            this.isShowRegion = true;
        }else{
            this.isShowRegion = false;
        }
    },
    uploadProtocolPreview(file){        //点击上传的协议图片，进行预览
        console.log('preview_file', file);
        this.protocolDialogImageUrl = file.url;
        this.protocolDialogVisible = true;

    },
    uploadProtocolSuccess(res){        //图片上传成功之后
        console.log('upload_file_success', this.enterpriseRate.protocolFileList);
        this.enterpriseRate.protocolFileList.push({uid:Date.now(), url:res.data.url, name: res.data.name });
    },
    removeProtocolImg(file){      //删除图片
        let protocol_file_list = this.enterpriseRate.protocolFileList;
        for(let i in protocol_file_list){
          if(protocol_file_list[i].url == file.url){      //根据图片名称来删除里面的图片，以图片url为准
            this.enterpriseRate.protocolFileList.splice(i,1)
          }
        }
    },
    submitEnterpriseRate(){         //保存编辑企业费率信息
        let post_data = {};
        if(this.enterpriseRate.standard_rate == ''){
            this.$message.error('企业标准费率不得为空');
            this.$refs.standard_rate.focus();
            return;
        }
        if(this.enterpriseRate.protocol_time && this.enterpriseRate.protocol_time.length > 0){        //如果协议合作时间不为空则传协议合作时间到后台
            post_data.protocol_time = {};
            post_data.protocol_time.protocol_start = this.enterpriseRate.protocol_time[0]/1000;//协议开始时间
            post_data.protocol_time.protocol_end =  this.enterpriseRate.protocol_time[1]/1000;          //协议结束时间
        }
        if(this.enterpriseRate.protocolFileList.length > 0){         //如果协议图片为空，则上传协议图片
            post_data.protocol_img = [];
            for(let val of this.enterpriseRate.protocolFileList){
              post_data.protocol_img.push(val.url);
            }
        }
        if(parseInt(this.enterpriseRate.region_type) > 0){           //如果费率政策大于0，则传 阶梯费率数据
            post_data.enterprise_region_rate = this.enterpriseRate.rate_list;
        }
        post_data.region_type = this.enterpriseRate.region_type;
        post_data.standard_rate = this.enterpriseRate.standard_rate;
        post_data.enterprise_facilitator_draft_id = this.select_enterprise_facilitator_draft_id;

        let {code, msg}   =   this.$api.sendSync(this.$mapapi.f_saveEnterpriseDraftRate, post_data);
        if(code != 200){
            this.$message.error(msg);
        }else{
            this.$message.success(msg);
        }
        this.query();
        this.editDialogTableVisible = false;
    },
    /* 查看/编辑协议费率部分 end */
    //审核
    check_modal_show(enterprise_facilitator_draft_id, enterprise_name) {
      this.check_show = true; //审核企业模态框显示
      this.check_enterprise_facilitator_draft_id = enterprise_facilitator_draft_id; //对应的审核企业ID
      this.check_enterprise_name = enterprise_name; //对应的审核企业名称
    },
    check() {
      let { code, msg } = this.$api.sendSync(
        this.$mapapi.f_checkEnterpriseDraftRate,
        {
          enterprise_facilitator_draft_id: this.check_enterprise_facilitator_draft_id,
          status: this.check_draft_status
        }
      );
      if (code != 200) this.$message.error(msg);
      this.$message.success(msg);
      this.check_show = false;
      this.query();
    },
  }
};
</script>


<style lang="less" :scope="true"  src="@/style/businessManagement/facilitator_enterprise_draft_list.less" >
</style>
